import axios from "axios";
import { MessageBox, Message } from "element-ui";
import store from "@/store";
import { getToken } from "@/utils/auth";

const service = axios.create({
    // baseURL: "http://172.18.1.190:8082",
    baseURL: "http://jssggxh.com:8082",
});

service.interceptors.request.use(
    (config) => {
        store.dispatch("user/setLoading", true);
        if (store.getters.token) {
            config.headers["token"] = getToken();
        }
        return config;
    },
    (error) => {
        // do something with request error
        console.log(error); // for debug
        return Promise.reject(error);
    }
);

service.interceptors.response.use(
    (response) => {
        const res = response.data;
        store.dispatch("user/setLoading", false);
        if (res.code !== 200) {
            const errMsg = res.msg || "请求失败";
            Message({
                message: errMsg,
                type: "error",
                duration: 3 * 1000,
            });
            if (
                res.code === 50008 ||
                res.code === 50012 ||
                res.code === 50014
            ) {
                MessageBox.confirm(
                    "You have been logged out, you can cancel to stay on this page, or log in again",
                    "Confirm logout",
                    {
                        confirmButtonText: "Re-Login",
                        cancelButtonText: "Cancel",
                        type: "warning",
                    }
                ).then(() => {
                    store.dispatch("user/resetToken").then(() => {
                        location.reload();
                    });
                });
            }
            return Promise.reject(new Error(errMsg));
        } else {
            console.log("请求成功");
            return res;
        }
    },
    (error) => {
        const { msg } = error.response.data;
        store.dispatch("user/setLoading", false);
        Message({
            message: msg || "请求失败",
            type: "error",
            duration: 3 * 1000,
        });
        return Promise.reject(error);
    }
);

export default service;
